import PySimpleGUI as sg
import telnetlib
import sys


def login(conn, username):
    is_login = False
    layout = [
        [sg.Text('电影推荐系统聊天室')],
        # [sg.Text('请输入昵称:'), sg.InputText(key='-username-')],
        [sg.Button('点击进入')]
    ]

    window = sg.Window('Chat', layout)
    while True:
        event, values = window.read()
        if event == '点击进入':
            # username = values['-username-'].strip()
            if username:
                try:
                    conn.open('127.0.0.1', 6666, timeout=10)
                except:
                    sg.popup('连接失败1')
                    break
                resp = conn.read_some()  # 读取服务器响应信息
                if resp != b'Connect Success':
                    sg.popup('连接失败2')
                    break
                conn.write(('login ' + username + '\n').encode())  # 向服务器发送登陆请求
                resp = conn.read_some()
                if resp == b'Username exists':
                    sg.popup('昵称已存在')
                else:
                    sg.popup('登陆成功')
                    is_login = True
                    break
            else:
                sg.popup('请输入用户名')
        if event in (None, 'Cancel'):
            break

    window.close()
    del window

    if is_login:
        chat(conn, username)


def chat(conn, username):
    layout = [
        [sg.Text('聊天窗口（' + username + ')')],
        [sg.Multiline(disabled=True, size=(80, 20), key='-chat-')],
        [sg.InputText(size=(70, 5), key='-message-'), sg.Button('发送消息')],
        [sg.Button('查询在线人数'), sg.Button('退出聊天室')]
    ]
    window = sg.Window('聊天室', layout)

    while True:
        event, values = window.read(timeout=10)  # 异步周期性更新
        if values:
            history_msg = values['-chat-']
            result = conn.read_very_eager().decode()
            if result.strip():
                if 'Online' in result:
                    sg.popup('当前在线用户', result)
                else:
                    window['-chat-'].update(history_msg + result.strip())
            if event in (None, '退出聊天室'):
                break
            elif event == '发送消息':
                send(conn, type='say', msg=values['-message-'])
                window['-message-'].update('')
            elif event == '查询在线人数':
                send(conn, type='look')

    print('窗口即将关闭')
    conn.write(b'logout\n')
    conn.close()
    window.close()


def send(conn, type=None, msg=None):
    if type == 'say':
        conn.write(('say ' + msg + '\n').encode())  # say后面有空格
    elif type == 'look':
        conn.write(b'look\n')


if __name__ == '__main__':
    conn = telnetlib.Telnet()
    username = sys.argv[0]
    login(conn, username)
